package cn.jx.cjm.codegenerator;

import cn.jx.cjm.codegenerator.base.SqlInfo;
import cn.jx.cjm.codegenerator.base.GenerateConfig;
import cn.jx.cjm.codegenerator.utils.YmlUtil;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.jx.cjm.codegenerator.FileBuild.buildBaseFile;
import static cn.jx.cjm.codegenerator.FileBuild.buildPomFile;
import static cn.jx.cjm.codegenerator.SqlBuild.*;

/**
 * 代码自动生成
 *
 * @author 陈加敏
 */
public class CodeGenerator {

    public static Map<String, List<TableInfo>> tableInfoMap = new HashMap<>();
    public static GenerateConfig generateConfig;


    /**
     * @param moduleTables 模块详情
     */
    public static void generateFiles(GenerateConfig generateConfig_, Map<String, String> moduleTables) throws Exception {
        generateConfig = generateConfig_;

        YmlUtil.loadYml(generateConfig.getYmlFile());

        SqlInfo sqlInfo = new SqlInfo();

        sqlInfo.setSqlUrl(YmlUtil.getValue(generateConfig.getSqlYmlPrefix() + ".url").toString());
        sqlInfo.setSqlDriverName(YmlUtil.getValue(generateConfig.getSqlYmlPrefix() + ".driver-class-name").toString());
        sqlInfo.setSqlUserName(YmlUtil.getValue(generateConfig.getSqlYmlPrefix() + ".username").toString());
        sqlInfo.setSqlPassword(YmlUtil.getValue(generateConfig.getSqlYmlPrefix() + ".password").toString());

        SqlBuild.moduleStartId = generateConfig.getPermissionStartId();

        for (Map.Entry<String, String> entry : moduleTables.entrySet()) {
            String moduleName = entry.getKey().split(",")[0];
            String[] tableNames = entry.getValue().split(",");
            for (String tableName : tableNames) {
                tableModuleMap.put(processEntityName(generateConfig.getTablePrefix(), tableName.trim()), moduleName);
            }
        }

        // 构建项目文件
        for (Map.Entry<String, String> entry : moduleTables.entrySet()) {
            String[] key = entry.getKey().split(",");

            String moduleName = key[0];
            String[] tableArr = entry.getValue().split(",");
            for (String tableName : tableArr) {
                TableInfo tableInfo = buildBaseFile(sqlInfo, moduleName, tableName);
                if (tableInfoMap.containsKey(entry.getKey())) {
                    tableInfoMap.get(entry.getKey()).add(tableInfo);
                } else {
                    List<TableInfo> tableInfoList = new ArrayList<>();
                    tableInfoList.add(tableInfo);
                    tableInfoMap.put(entry.getKey(), tableInfoList);
                }
            }
        }


        // 打印权限表sql
        int parentId;
        int menuSort = 1;
        for (Map.Entry<String, List<TableInfo>> entry : tableInfoMap.entrySet()) {
            String[] key = entry.getKey().split(",");
            String moduleName = key[0];
            String moduleCommon = key[1];
            parentId = SqlBuild.moduleStartId++;
            permissionSql.add(getPermissionSql(parentId, null, moduleName, moduleCommon, null, null, "/" + moduleName, moduleName, "/" + moduleName + "/" + processEntityName(generateConfig.getTablePrefix(), entry.getValue().get(0).getName()), "Layout", "tree", menuSort++, "menu", null));
            int pageSort = 1;
            for (TableInfo tableInfo : entry.getValue()) {
                buildSql(pageSort++ , parentId, moduleName, tableInfo);
            }

        }
        printSql();


        if (generateConfig.getDisperseModule()) {
            for (Map.Entry<String, String> entry : moduleTables.entrySet()) {
                String[] key = entry.getKey().split(",");
                String moduleName = key[0];
                buildPomFile("keiskei-" + moduleName);
            }
            buildPomFile(generateConfig.getProjectPath());
        }

    }

    public static Map<String, String> TEMPLATES = new HashMap<>();

    static {
        TEMPLATES.put("Request", "dto/request/");
        TEMPLATES.put("Response", "dto/response/");
        TEMPLATES.put("SupportService", "support/");

    }


    /**
     * 表名转实体类
     *
     * @param tablePrefixes 表前缀
     * @param field         表名
     * @return .
     */
    public static String processEntityName(String[] tablePrefixes, String field) {
        StringBuilder sb = new StringBuilder(field.length());
        for (String tablePrefix : tablePrefixes) {
            field = field.replaceAll(tablePrefix, "");
        }
        String[] fields = field.split("_");
        String temp;
        sb.append(fields[0]);
        for (int i = 1; i < fields.length; i++) {
            temp = fields[i].trim();
            sb.append(temp.substring(0, 1).toUpperCase()).append(temp.substring(1));
        }
        return sb.toString();
    }


    public static String processEntityName(String field) {
        return field.substring(0, 1).toLowerCase() + field.substring(1);
    }

}
